import apiStopLivePlay from '../../../yali-sdk/business/live/api/apiStopLivePlay';
import { SUCCESS } from '../../../yali-sdk/utils/success';
import frequentClick from '../../../yali-sdk/utils/frequentClick';
import getIn from '../../../yali-sdk/utils/getIn';
import { filterImg } from '../../imgBaseUrl';
import { addNotifier, notify, removeNotifier } from '../../../yali-sdk/utils/NotifyRegistryCenter';
import apiLiveList from '../../../yali-sdk/business/live/api/apiAnchorLives';
import formattingDate from '../../../yali-sdk/utils/formattingDate';
import _list from '../../../yali-sdk/utils/list';
import { LIVE_STATUS_END, LIVE_STATUS_START, LIVE_STATUS_WAIT } from '../../../yali-sdk/business/live/api/constrants';
import { getYaliUserInfo } from '../../../utils/checkAuth';

Page({
    data: {
        isLoaded: false,
        item: undefined,
        anchor: undefined,
    },
    onLoad() {
        this.liveList = new _list((params, cb) => global.actionDispatcher.execute(apiLiveList, params, cb), (core) => {
            const isLoaded = core.getIsLoaded();
            const isLoading = core.getIsLoading();
            const hasNext = core.getHasNext();
            let item = this.data.item;
            if (isLoaded) {
                item = core.getScrollList().get(0);
                item = item ? item.toJS() : {};
                wx.hideLoading();
                wx.stopPullDownRefresh();
            }
            this.setData({
                item,
                isLoaded,
                isLoading,
                hasNext,
                statusClass: item.status === LIVE_STATUS_WAIT ? 'status-wait' : (item.status === LIVE_STATUS_START ? 'status-start' : (item.status === LIVE_STATUS_END ? 'status-end' : '')),
                statusColor: item.status === LIVE_STATUS_WAIT ? '#f7079a' : (item.status === LIVE_STATUS_START ? '#ff3c31' : (item.status === LIVE_STATUS_END ? '#999' : '')),
            });
        }, { filter: list => list && list.map(it => it
                .set('_end_time', formattingDate('yy/MM/dd hh:mm', new Date(it.get('end_time') * 1000)))
                .update('anchor', v => filterImg(v, 'head_photo'))
                .set('_start_time', formattingDate('yy/MM/dd hh: mm', new Date(it.get('start_time') * 1000)))
                .update('shop_logo', v => filterImg({ v }, 'v').v)
                .updateIn(['products', 'list'], list => list && list.map(it => filterImg(it, 'pic')))) });
        addNotifier('UPDATE_LIVES_STATUS', this.refreshStatus, this);
        addNotifier('UPDATE_LIVES_CURRENT_PRODUCT', this.refreshCurrentProduct, this);// 修改当前显示的产品
        addNotifier('UPDATE_PRODUCT_PRICE', this.refreshProductPrice, this);// 修改价格
    },
    onUnload() {
        removeNotifier('UPDATE_LIVES_STATUS', this.refreshStatus, this);
        removeNotifier('UPDATE_LIVES_CURRENT_PRODUCT', this.refreshCurrentProduct, this);
        removeNotifier('UPDATE_PRODUCT_PRICE', this.refreshProductPrice, this);
    },
    // 更新活动状态
    refreshStatus(params) {
        if (params && params.liveId && params.status !== undefined) {
            const item = { ...this.data.item, status: params.status, current_room: params.roomId };
            this.setData({
                item,
                statusClass: item.status === LIVE_STATUS_WAIT ? 'status-wait' : (item.status === LIVE_STATUS_START ? 'status-start' : (item.status === LIVE_STATUS_END ? 'status-end' : '')),
                statusColor: item.status === LIVE_STATUS_WAIT ? '#f7079a' : (item.status === LIVE_STATUS_START ? '#ff3c31' : (item.status === LIVE_STATUS_END ? '#999' : '')),
            });
        }
    },
    // 更新活动当前推荐产品
    refreshCurrentProduct(params) {
        if (params && params.liveId && params.productId !== undefined && this.data.item) {
            this.setData({ item: { ...this.data.item, current_product: params.productId } });
        }
    },
    // 更新产品价格
    refreshProductPrice(params) {
        const list = getIn(this.data.item, ['products', 'list']);
        if (params && params.unitPrice !== undefined && params.productId !== undefined && list) {
            this.data.item.products.list = list.map(it => ((it.id === params.productId) ? { ...it, unit_price: params.unitPrice } : it));
            this.setData({ item: this.data.item });
        }
    },
    onReady() {
        getYaliUserInfo().then((user) => {
            this.setData({
                isVisitor: getIn(this.options, ['isVisitor']) || getIn(user, ['isVisitor']) || false,
                uId: user.id,
            }, () => {
                const options = this.options || {};
                if (typeof options.item === 'string') {
                    const item = JSON.parse(options.item) || undefined;
                    this.setData({
                        item,
                    });
                    item && this.onLoadLives(item);
                }
            });
        });
    },
    onPullDownRefresh() {
        if (!this.data.item || !this.data.item.id || this.data.isLoading) return;
        this.onLoadLives(this.data.item);
    },
    // 主播操作：开始
    startPlay() {
        frequentClick().then(() => {
            const liveId = getIn(this.data.item, ['id']);
            const username = getIn(this.data.item, ['anchor', 'name']);
            if (!liveId || !username) return;
            // 获取直播配置信息
            const url = `/pages/anchor/room/room?item=${JSON.stringify(this.data.item)}&id=${liveId}`;
            wx.navigateTo({
                url,
            });
        });
    },
    endPlay() {
        const total_people =getIn(this.data.item,['total_visitor']);
        const point_praise =getIn(this.data.item,['total_live_zan']);
        frequentClick().then(() => {
            wx.showModal({
                title: '温馨提示',
                content: '确定结束这场直播?',
                success: (res) => {
                    if (res.confirm === true) {
                        const liveId = getIn(this.data.item, ['id']);
                        global.actionDispatcher.execute(apiStopLivePlay, { liveId,total_people,point_praise}, (f, fs) => {
                            if (f === SUCCESS) {
                                notify('UPDATE_LIVES_STATUS', { liveId, status: LIVE_STATUS_END });
                                wx.showToast({ title: getIn(fs, ['msg']) || '操作成功' });
                            }
                        });
                    }
                },
            });
        });
    },
    // 观众点击播放
    onPlaying() {
        frequentClick().then(() => {
            const liveId = getIn(this.data.item, ['id']);
            if (!liveId) return;
            // 获取直播配置信息
            const url = `/pages/audience/room/room?id=${liveId}`;
            wx.navigateTo({
                url,
            });
        });
    },
    onLoadLives(item) {
        wx.showLoading({ mask: true });
        this.liveList.loadNew({
            anchorId: item.anchor_id,
            isAnchor: true,
            isProduct: true,
            id: item.id,
        });
    },
});
